using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;
using System.IO;

using EntitySpaces.Interfaces;

using AutoBase.BusinessObjects;
using AutoBase.Shared;

namespace WebControl.VehicleSearch
{
    public partial class VechicleDetails : System.Web.UI.UserControl
    {
        private int staffId = -2;
        private string mediaPath = "http://media.autobase.co.nz/";

        public string BackUrl
        {
            get
            {
                object o = this.ViewState["_BackUrl"];
                if (o != null)
                {
                    return (string)this.ViewState["_BackUrl"];
                }
                else
                {
                    return "";
                }
            }

            set
            {
                this.ViewState["_BackUrl"] = value;
            }
        }

        public string PrinterFriendlyUrl
        {
            get
            {
                object o = this.ViewState["_PrinterFriendlyUrl"];
                if (o != null)
                {
                    return (string)this.ViewState["_PrinterFriendlyUrl"];
                }
                else
                {
                    return "";
                }
            }

            set
            {
                this.ViewState["_PrinterFriendlyUrl"] = value;
            }
        }

        public long VehicleId
        {
            get
            {
                object o = this.ViewState["_VehicleId"];
                if (o != null)
                {
                    return (long)this.ViewState["_VehicleId"];
                }
                else
                {
                    return -1;
                }
            }

            set
            {
                this.ViewState["_VehicleId"] = value;
            }
        }

        public int BranchId
        {
            get
            {
                object o = this.ViewState["_BranchId"];
                if (o != null)
                {
                    return (int)this.ViewState["_BranchId"];
                }
                else
                {
                    return -1;
                }
            }

            set
            {
                this.ViewState["_BranchId"] = value;
            }
        }

        public int StaffId
        {
            get
            {
                return staffId;
            }
            set
            {
                staffId = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterClientScript();
            if (VehicleExists(VehicleId))
            {
                divNoVehicle.Visible = false;
                divMain.Visible = true;

                //Print Vehicle Card
                PrinterFriendlyUrl = (string.IsNullOrEmpty(PrinterFriendlyUrl) ? "" : PrinterFriendlyUrl + "?vehicle_id=" + VehicleId.ToString());
            }
            else
            {
                divNoVehicle.Visible = true;
                divMain.Visible = false;
                programmaticPopup.Visible = false;
            }

            if (!Page.IsPostBack)
            {
                dealerModalPopup.Hide();
            }
            LoadImages(VehicleId);
            LoadVehicleDetails(VehicleId);
            LoadLightBox(VehicleId);
        }

        private void ClearDealerModalPopup()
        {
            uicMessage.Text = string.Empty;
            uicName.Text = string.Empty;
            uicEmail.Text = string.Empty;
            uicPhone.Text = string.Empty;
            uicMobile.Text = string.Empty;
        }

        private void RegisterClientScript()
        {

            // javascript
            HtmlGenericControl Include;
            Include = new HtmlGenericControl("script");
            Include.Attributes.Add("type", "text/javascript");
            Include.Attributes.Add("src", "App_Themes/Default/lightbox/lightbox.js");
            this.Page.Header.Controls.Add(Include);

            //// stylesheet
            Include = new HtmlGenericControl("link");
            Include.Attributes.Add("type", "text/css");
            Include.Attributes.Add("href", AutoBase.Shared.SystemSetting.UrlPublicSite + "App_Themes/Default/lightbox/lightbox.css");
            this.Page.Header.Controls.Add(Include);
        }

        private bool VehicleExists(long vehicleId)
        {
            ViewVehiclesRetail vehicle = new ViewVehiclesRetail();
            vehicle.Query.Where(vehicle.Query.Id.Equal(vehicleId));
            return vehicle.Query.Load();
        }

        public void LoadImages(long vehicleId)
        {
            ArrayList vehicleImages = new ArrayList();
            VehicleFunctions vehicleFunctions = new VehicleFunctions();
            VehicleImageCollection vehicleImage = new VehicleImageCollection();
            vehicleImage.Query.Where(vehicleImage.Query.VehicleId.Equal(vehicleId), vehicleImage.Query.ImageIndex.NotEqual(100));
            vehicleImage.Query.OrderBy(vehicleImage.Query.VehicleId.Ascending);
            vehicleImage.Query.OrderBy(vehicleImage.Query.ImageIndex.Ascending);
            string largeImageUrl = string.Empty;
            string thumbImageUrl = string.Empty;

            if (vehicleImage.Query.Load())
            {
                foreach (VehicleImage vehicleImg in vehicleImage)
                {
                    largeImageUrl = vehicleFunctions.GetVehicleImagePath(vehicleId, (short)vehicleImg.ImageIndex, VehicleFunctions.VehicleImageSize.Large, FileFunctions.FilePathType.HttpFullPath);
                    thumbImageUrl = vehicleFunctions.GetVehicleImagePath(vehicleId, (short)vehicleImg.ImageIndex, VehicleFunctions.VehicleImageSize.Medium, FileFunctions.FilePathType.HttpFullPath);
                    vehicleImages.Add(largeImageUrl + "~" + thumbImageUrl + "~" + vehicleImg.ImageIndex.ToString());
                }
            }

            repeaterVehicleImages.DataSource = vehicleImages;
            repeaterVehicleImages.DataBind();
        }

        public void LoadDealerContactDetails(int branchId, long vehicleId)
        {
            string imageLocator = string.Empty;
            string imageLogo = string.Empty;
            PhoneFunctions phoneFunctions = new PhoneFunctions();
            StaffCollection staffs = new StaffCollection();
            Staff staff = new Staff();
            Branch branch = new Branch();

            Functions dd = new Functions();

            if (!branch.LoadByPrimaryKey(branchId))
            {
                this.divError.Visible = true;
                this.divDealer.Visible = false;
            }
            else
            {
                uicHeader.Text = branch.TradingName;
                uicBack.NavigateUrl = "../" + BackUrl;
                uicPrint.NavigateUrl = "../" + PrinterFriendlyUrl;
                uicDealer.Text = branch.TradingName;

                this.divError.Visible = false;
                this.divDealer.Visible = true;

                this.lblAddress.InnerHtml = "";
                if (branch.Address.Length > 0)
                {
                    this.lblAddress.InnerHtml = branch.Address;
                }
                if (branch.Suburb.Length > 0)
                {
                    this.lblAddress.InnerHtml += (this.lblAddress.InnerHtml.Length > 0) ? "<br/>" + branch.Suburb : branch.Suburb;
                }
                if (branch.City.Length > 0)
                {
                    this.lblAddress.InnerHtml += (this.lblAddress.InnerHtml.Length > 0) ? "<br/>" + branch.City : branch.City;
                }
                if (branch.Phone.Length > 0)
                {
                    this.lblPhone.InnerHtml = phoneFunctions.FormatNumberList(branch.Phone, " Or ");
                }

                // Load the Staff Member : Try to load by staff ID first.
                staff.Query.Where(staff.Query.Id.Equal(staffId));

                if (staff.Query.Load())
                {
                    DisplayStaffDetails(staff, branchId);
                }
                else  // Staff not found -> Load the all the staff.  
                {
                    //this.staff.Query.Where.WhereClauseReset();

                    staffs.Query.Where(staffs.Query.BranchId.Equal(branchId));

                    staffs.Query.Where(staffs.Query.Status.GreaterThan((Int16)Enums.RecordStatus.Deleted));

                    staffs.Query.Where(staffs.Query.RoleIsSales.Equal(1));

                    staffs.Query.OrderBy(staff.Query.DisplayOrder.Ascending);
                    staffs.Query.OrderBy(staff.Query.Name.Ascending);
                    string temp = "";
                    divName.Visible = false;
                    if (staffs.Query.Load())
                    {
                        if (staffs.Count > 0)
                        {
                            divName.Visible = true;

                            foreach (Staff singleStaff in staffs)
                            {
                                if (singleStaff.Name.Length > 0)
                                {
                                    temp += singleStaff.Name + "<br/>";
                                }
                                if (singleStaff.Mobile.Length > 0)
                                {
                                    temp += "<small>Mobile:&nbsp;" + phoneFunctions.FormatNumberList(singleStaff.Mobile, " Or ") + "</small>&nbsp;";
                                }
                                if (singleStaff.WorkPhone.Length > 0)
                                {
                                    temp += "<small>Ph:&nbsp;" + phoneFunctions.FormatNumberList(singleStaff.WorkPhone, " Or ") + "</small>";
                                }
                                temp += "<br/>";
                            }

                            if (temp.Length > 0)
                            {
                                lblStaffName.InnerHtml = temp;
                            }
                        }
                    }
                }
            }
        }

        private void DisplayStaffDetails(Staff staff, int branchId)
        {
            PhoneFunctions phoneFunctions = new PhoneFunctions();
            divName.Visible = false;
            divName.Visible = true;

            if (staff.Name.Length > 0)
            {
                lblStaffName.InnerHtml += staff.Name;
            }
            if (staff.Mobile.Length > 0)
            {
                lblStaffName.InnerHtml += "&nbsp&nbspMob:" + phoneFunctions.FormatNumberList(staff.Mobile, " Or ");
            }

        }

        public void LoadLightBox(long vehicleId)
        {
            if (vehicleId <= 0)
            {
                return;
            }
            //HtmlImage image;
            HtmlImage image;
            HtmlTable table = new HtmlTable();
            HtmlTableCell cell;
            HtmlTableRow row;
            VehicleFunctions vehicleFunctions = new VehicleFunctions();
            int maxCol = 0;
            int maxRow = 7;
            int imageCount = 0;
            int picArrayIndex = 0;

            VehicleImageCollection vehicleImage = new VehicleImageCollection();
            vehicleImage.Query.Where(vehicleImage.Query.VehicleId.Equal(vehicleId), vehicleImage.Query.ImageIndex.NotEqual(100));

            vehicleImage.Query.OrderBy(vehicleImage.Query.VehicleId.Ascending);

            if (!vehicleImage.Query.Load())
            {
                return;
            }

            if (vehicleImage.Count > 14)
            {
                maxCol = 3;
            }
            else if (vehicleImage.Count > 7)
            {
                maxCol = 2;
            }
            else
            {
                maxCol = 1;
                maxRow = vehicleImage.Count;
            }

            // Build the image array Javascrip
            string javaScript = string.Empty;
            javaScript += "<script language=\"JavaScript\" type=\"text/ecmascript\" >";
            javaScript += "var picArray = new Array();";
            javaScript += "var imageColumnCount = " + maxCol + "; ";

            lightboxThumbs.Rows.Add(new HtmlTableRow());

            int position = 0;

            cell = new HtmlTableCell();
            cell.VAlign = "top";
            lightboxThumbs.Rows[0].Cells.Add(cell);

            table = new HtmlTable();
            table.CellPadding = 0;
            table.CellSpacing = 0;
            table.Border = 0;

            cell.Controls.Add(table);

            foreach (VehicleImage vehicleImg in vehicleImage)
            {
                Math.DivRem((short)vehicleImg.ImageIndex, 8, out position);

                if (position == 0)
                {
                    cell = new HtmlTableCell();
                    cell.VAlign = "top";
                    lightboxThumbs.Rows[0].Cells.Add(cell);

                    table = new HtmlTable();
                    table.CellPadding = 0;
                    table.CellSpacing = 0;
                    table.Border = 0;

                    cell.Controls.Add(table);
                }
                imageCount++;

                row = new HtmlTableRow();
                table.Rows.Add(row);

                cell = new HtmlTableCell();
                row.Cells.Add(cell);

                picArrayIndex = imageCount - 1;

                //image = new HtmlImage();
                //image.Src = vehicleFunctions.GetVehicleImagePath(vehicleId, (short)vehicleImg.ImageIndex, VehicleFunctions.VehicleImageSize.Thumb, FileFunctions.FilePathType.HttpFullPath);
                ////image.Attributes.Add("Src", vehicleFunctions.GetVehicleImagePath(vehicleId, (short)vehicleImg.ImageIndex, VehicleFunctions.VehicleImageSize.Thumb, FileFunctions.FilePathType.HttpFullPath));
                //image.Attributes.Add("name", "lightboxThumb" + picArrayIndex);
                ////image.Attributes.Add("id", "lightboxThumb" + picArrayIndex); //REX
                ////image.Attributes.Add("id", picArrayIndex.ToString());
                //image.ID = picArrayIndex.ToString();
                //image.Attributes.Add("onClick", "setLightboxMainImage(" + picArrayIndex + ");selectLightboxThumb(" + picArrayIndex + ");");
                //image.Attributes.Add("class", "lightboxThumb");

                HtmlImage _img = new HtmlImage();
                _img.Attributes.Add("name", "lightboxThumb" + picArrayIndex);
                _img.Attributes.Add("id", "lightboxThumb" + picArrayIndex.ToString());
                //_img.Attributes.Add("Src", vehicleFunctions.GetVehicleImagePath(vehicleId, (short)vehicleImg.ImageIndex, VehicleFunctions.VehicleImageSize.Thumb, FileFunctions.FilePathType.HttpFullPath));
                _img.Src = vehicleFunctions.GetVehicleImagePath(vehicleId, (short)vehicleImg.ImageIndex, VehicleFunctions.VehicleImageSize.Thumb, FileFunctions.FilePathType.HttpFullPath);
                _img.Attributes.Add("onClick", "setLightboxMainImage(" + picArrayIndex + ");selectLightboxThumb(" + picArrayIndex + ");");
                _img.Attributes.Add("class", "lightboxThumb");

                cell.Controls.Add(_img);




                //javaScript += "picArray[" + picArrayIndex.ToString() + "] = new Image();";
                javaScript += "picArray[" + picArrayIndex.ToString() + "] = '" + vehicleFunctions.GetVehicleImagePath(vehicleId, (short)vehicleImg.ImageIndex, VehicleFunctions.VehicleImageSize.Large, FileFunctions.FilePathType.HttpFullPath) + "';";

                if (imageCount >= vehicleImage.Count)
                {
                    break;
                }
            }


            // End of image array Javascrip
            javaScript += "</script>";

            // Set the first large image
            lightboxMainImage.Src = vehicleFunctions.GetVehicleImagePath(vehicleId, 1, VehicleFunctions.VehicleImageSize.Large, FileFunctions.FilePathType.HttpFullPath);

            if (!this.IsPostBack)
            {
                // Set the image array Javascrip
                placeHolderJs.Controls.Add(new LiteralControl(javaScript));
            }

        }

        public void LoadVehicleDetails(long vehicleId)
        {
            ViewVehiclesRetail vehicle = new ViewVehiclesRetail();
            List<KeyValuePair<string, string>> vehicleDetails = new List<KeyValuePair<string, string>>();
            decimal decimalVal = 0;
            vehicle.Query.Where(vehicle.Query.Id.Equal(vehicleId));
            if (vehicle.Query.Load())
            {
                BranchId = (int)vehicle.BranchId;
                Branch branch = new Branch();
                branch.Query.Where(branch.Query.Id.Equal(vehicle.BranchId));
                LoadDealerContactDetails(BranchId, vehicleId);
                branch.Query.Load();

                if (vehicle.Year > 0)
                {
                    labelTitle.Text = vehicle.Year.ToString() + " " + vehicle.ManufacturerName + " " + vehicle.ModelName + " " + vehicle.ModelDetail;
                }
                else
                {
                    labelTitle.Text = vehicle.ManufacturerName + " " + vehicle.ModelName + " " + vehicle.ModelDetail;
                }

                trStockNo.Visible = true;
                uicStockNo.InnerHtml = vehicle.StockNumber;

                trType.Visible = true;
                uicType.InnerHtml = vehicle.VehicleTypeName;

                trExtColour.Visible = false;
                if (!vehicle.ExtColour.ToLower().StartsWith("n/a") && vehicle.ExtColour.Length > 0)
                {
                    trExtColour.Visible = true;
                    uicExtColour.InnerHtml = vehicle.ExtColour;
                }

                trIntType.Visible = false;
                if (!vehicle.InteriorDetails.ToLower().StartsWith("n/a") && vehicle.InteriorDetails.Length > 0)
                {
                    trIntType.Visible = true;
                    uicIntType.InnerHtml = vehicle.InteriorDetails;
                }

                trTransmission.Visible = true;
                uicTransmission.InnerHtml = vehicle.Transmission;

                trFuel.Visible = false;
                if (vehicle.FuelType.Length > 0)
                {
                    uicFuel.InnerHtml = vehicle.FuelType;
                    trFuel.Visible = true;
                }

                trCC.Visible = false;
                if (vehicle.CcRating > 0)
                {
                    trCC.Visible = true;
                    uicCC.InnerHtml = vehicle.CcRating + " cc";
                }

                trODO.Visible = false;
                if (vehicle.Odometer > 0)
                {
                    trODO.Visible = true;
                    uicOdo.InnerHtml = string.Format("{0:#,0}", vehicle.Odometer);
                }

                trCondition.Visible = false;
                if (!vehicle.Condition.ToLower().StartsWith("n/a") && vehicle.Condition.Length > 0)
                {
                    trCondition.Visible = true;
                    uicCondition.InnerHtml = vehicle.Condition;
                }

                trChassis.Visible = false;
                if (vehicle.ChassisNumber.Length > 0)
                {
                    trChassis.Visible = true;
                    uicChassis.InnerHtml = vehicle.ChassisNumber;
                }

                trDifferential.Visible = false;
                if (vehicle.Differential.Length > 0)
                {
                    trDifferential.Visible = true;
                    uicDiff.InnerHtml = vehicle.Differential;
                }

                trWheelBase.Visible = false;
                if (vehicle.WheelBase.ToString().Length > 0 && vehicle.WheelBase > 0)
                {
                    trWheelBase.Visible = true;
                    uicWb.InnerHtml = string.Format("{0:#,0.00}", (vehicle.WheelBase / 100)) + " m";
                }

                trPayload.Visible = false;
                if (vehicle.Payload.ToString().Length > 0 && vehicle.Payload > 0)
                {
                    trPayload.Visible = true;
                    uicPayLoad.InnerHtml = string.Format("{0:#,00}", vehicle.Payload) + " kg";
                }

                trTare.Visible = false;
                if (vehicle.Tare.ToString().Length > 0 && vehicle.Tare > 0)
                {
                    trTare.Visible = true;
                    uicTare.InnerHtml = string.Format("{0:#,0}", vehicle.Tare) + " kg";
                }

                trDisplacement.Visible = false;
                if (vehicle.Gvm.ToString().Length > 0 && vehicle.Gvm > 0)
                {
                    trDisplacement.Visible = true;
                    uicDisplacement.InnerHtml = string.Format("{0:#,00}", vehicle.Gvm) + " kg";
                    if (vehicle.CategoryId != (int)VehicleFunctions.VehicleCategories.Boat)
                    {
                        uicDisplacementTitle.InnerHtml = "GVM:";
                    }
                }

                trTyreSize.Visible = false;
                if (vehicle.TyreSize.Length > 0)
                {
                    trTyreSize.Visible = true;
                    uicTyreSize.InnerHtml = vehicle.TyreSize;
                }

                trAxleConfiguration.Visible = false;
                if (vehicle.AxleConfiguration.Length > 0 && vehicle.AxleConfiguration != "")
                {
                    trAxleConfiguration.Visible = true;
                    uicAxle.InnerHtml = vehicle.AxleConfiguration;
                }

                trEngine.Visible = false;
                if (vehicle.EngineDetails.Length > 0)
                {
                    trEngine.Visible = true;
                    uicEngine.InnerHtml = vehicle.EngineDetails;
                }

                trHorsepower.Visible = false;
                if (vehicle.Horsepower > 0)
                {
                    trHorsepower.Visible = true;
                    uicHP.InnerHtml = string.Format("{0:#,#.#}", vehicle.Horsepower);
                }

                trDeckLength.Visible = false;

                if (vehicle.DeckLength.ToString().Length > 0 && vehicle.DeckLength > 0)
                {
                    trDeckLength.Visible = true;
                    decimalVal = decimal.Parse(vehicle.DeckLength.ToString());
                    uicDeckLength.InnerHtml = string.Format("{0:#,0.00}", (decimalVal / 100)) + " m";
                }

                trLength.Visible = false;
                if (vehicle.Length.ToString().Length > 0 && vehicle.Length > 0)
                {
                    trLength.Visible = true;
                    decimalVal = decimal.Parse(vehicle.Length.ToString());
                    uicLength.InnerHtml = string.Format("{0:#,0.00}", (decimalVal / 100)) + " m";
                }

                trHeight.Visible = false;
                if (vehicle.Height.ToString().Length > 0 && vehicle.Height > 0)
                {
                    trHeight.Visible = true;
                    decimalVal = decimal.Parse(vehicle.Height.ToString());
                    uicHeightData.InnerHtml = string.Format("{0:#,0.00}", (decimalVal / 100)) + " m";
                    if (vehicle.CategoryId == (int)VehicleFunctions.VehicleCategories.Boat)
                    {
                        uicHeight.InnerHtml = "Draft:";
                    }
                }

                trWidth.Visible = false;
                if (vehicle.Width.ToString().Length > 0 && vehicle.Width > 0)
                {
                    trWidth.Visible = true;
                    decimalVal = decimal.Parse(vehicle.Width.ToString());
                    uicWidthData.InnerHtml = string.Format("{0:#,0.00}", (decimalVal / 100)) + " m";
                    if (vehicle.CategoryId == (int)VehicleFunctions.VehicleCategories.Boat)
                    {
                        uicWidth.InnerHtml = "Beam:";
                    }
                }

                trSeats.Visible = false;
                if (vehicle.Seats.ToString().Length > 0 && vehicle.Seats > 0)
                {
                    trSeats.Visible = true;
                    uicSeats.InnerHtml = vehicle.Seats.ToString();
                }

                trFuelCapacity.Visible = false;
                if (vehicle.FuelCapacity.ToString().Length > 0 && vehicle.FuelCapacity > 0)
                {
                    trFuelCapacity.Visible = true;
                    uicFuelCapacity.InnerHtml = string.Format("{0:#,00}", vehicle.FuelCapacity) + " ltr";
                }

                if (vehicle.Comments != "")
                {
                    trComments.Visible = true;
                    uicComments.InnerHtml = vehicle.Comments;
                }

                //Promotions
                if ((bool)vehicle.ApplyStandardText)
                {
                    if (branch.StandardVehicleText.Length > 0)
                    {
                        trComments.Visible = true;
                        if (uicComments.InnerHtml.Length > 0)
                        {
                            uicComments.InnerHtml = uicComments.InnerHtml + "<br/><br/>" + branch.StandardVehicleText;
                        }
                        else
                        {
                            uicComments.InnerHtml = branch.StandardVehicleText;
                        }
                    }
                }

                if (branch.WebUrl.Length > 0)
                {
                    uicWww.NavigateUrl = branch.WebUrl;
                    uicWww.Text = "visit our website " + branch.WebUrl;
                }

                ViewVehicleFeatureCollection vehicleFeatures = new ViewVehicleFeatureCollection();
                vehicleFeatures.Query.Where(vehicleFeatures.Query.VehicleId.Equal(vehicle.Id));
                vehicleFeatures.Query.Select(vehicleFeatures.Query.Feature);

                if (vehicleFeatures.Query.Load())
                {
                    divOptions.Visible = true;
                    RepeaterFeatures.DataSource = vehicleFeatures;
                    RepeaterFeatures.DataBind();
                }
                else
                {
                    divOptions.Visible = false;
                }
            }

        }

        protected void uicButton_Click(object sender, ImageClickEventArgs e)
        {
            ImageButton thisControl = (ImageButton)sender;

            if (thisControl.ID.Equals("uicSend"))
            {

                try
                {
                    if (Page.IsValid)
                    {
                        SendMessage();
                        dealerModalPopup.Hide();
                        ClearDealerModalPopup();
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

        }

        protected void CustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = true;
            try
            {
                switch (((CustomValidator)source).ID)
                {
                    case "RequiredFieldValidator1":
                        break;

                    default:
                        break;
                }
            }
            catch (ArgumentNullException)
            {
                args.IsValid = false;
            }
            catch (FormatException)
            {
                args.IsValid = false;
            }
            catch (OverflowException)
            {
                args.IsValid = false;
            }
        }

        private void SendMessage()
        {
            Functions functions = new Functions();
            String enquiryText = functions.SetDBText(uicMessage.Text.Trim());

            Branch branch = new Branch();
            branch.Query.Where(branch.Query.Id.Equal(BranchId));

            if (branch.Query.Load())
            {
                // Load all the staff the email has to go to; All Defult and Sales staff
                StaffCollection staffs = new StaffCollection();

                staffs.Query.Where(staffs.Query.BranchId.Equal(BranchId));
                staffs.Query.Where(staffs.Query.Status.NotEqual((Int16)Enums.RecordStatus.Deleted));
                staffs.Query.Where(new esWhereItem(esParenthesis.Open));
                staffs.Query.Where(staffs.Query.RoleIsAdmin.Equal(1));
                staffs.Query.Or(staffs.Query.RoleIsSales.Equal(1));
                staffs.Query.Where(new esWhereItem(esParenthesis.Close));

                staffs.Query.Load();

                foreach (Staff staff in staffs)
                {
                    String mailBody = GetBranchEnquiryBodyText(
                           branch.TradingName,
                           uicName.Text,
                           uicPhone.Text,
                           uicMobile.Text,
                           uicEmail.Text,
                           functions.SetDBText(uicMessage.Text.Trim()),
                           staff.EmailIsHtml);
                    SendEmail(staff.Email, mailBody, "AUTOBASE Enquiry", staff.EmailIsHtml.Value);
                }

                //CookieStore.Daily_Contact_Count = CookieStore.Daily_Contact_Count + 1;
            }
        }

        private void SendEmail(String To, String Body, String Subject, Boolean IsHTML)
        {
            MailFunctions mails = new MailFunctions();
            mails.SendEmail(AutoBase.Shared.SystemSetting.EmailMailAgentName + "~" + AutoBase.Shared.SystemSetting.EmailMailAgentAddress,
                To,
                "",
                Subject,
                Body);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="list">BranchTradingName, FromName, FromPhone, FromMobile, FromEmail, EnquiryDetails, IsHTML</param>
        /// <returns>Formatted HTML or text for an email body</returns>
        public static string GetBranchEnquiryBodyText(params object[] list)
        {

            StringBuilder returnVal = new StringBuilder();

            string fileName = "";

            string tradingName = (string)list[0];
            string fromName = (string)list[1];
            string fromPhone = (string)list[2];
            string fromMobile = (string)list[3];
            string fromEmail = (string)list[4];
            string details = (string)list[5];
            bool isHTML = (Boolean)list[6];

            fileName = AutoBase.Shared.SystemSetting.EmailTemplateFolder + @"Autobase\Enquiries\BranchEnquiry" + (isHTML ? ".htm" : ".txt");

            try
            {
                if (File.Exists(fileName))
                {
                    returnVal.Insert(0, File.ReadAllText(fileName));

                    returnVal.Replace("<%BranchTradingName%>", tradingName);
                    returnVal.Replace("<%FromName%>", fromName);
                    returnVal.Replace("<%FromPhone%>", fromPhone);
                    returnVal.Replace("<%FromMobile%>", fromMobile);
                    returnVal.Replace("<%FromEmail%>", fromEmail);
                    returnVal.Replace("<%EnquiryDetails%>", details);
                    returnVal.Replace("<%Subject%>", "Autobase Inquiry");
                    return returnVal.ToString();
                }

                return "Error locating email template" + fileName;
            }
            catch (System.IO.IOException ex)
            {
                throw ex;
            }
        }

        protected void RepeaterFeatures_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item ||
                e.Item.ItemType == ListItemType.AlternatingItem)
            {
                ViewVehicleFeature vehicleFeatures = (ViewVehicleFeature)e.Item.DataItem;
                HtmlGenericControl liVehicleFeature = ((HtmlGenericControl)e.Item.FindControl("liVehicleFeature"));
                if (liVehicleFeature != null)
                {
                    liVehicleFeature.InnerHtml = vehicleFeatures.Feature;
                }
            }
        }

        protected void repeaterVehicleImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            string largeImageUrl = string.Empty;
            string thumbImageUrl = string.Empty;
            string vehiclmageUrl = string.Empty;
            string vehicleIndex = string.Empty;

            if (e.Item.ItemType == ListItemType.Item ||
                e.Item.ItemType == ListItemType.AlternatingItem)
            {
                vehiclmageUrl = (string)e.Item.DataItem;
                largeImageUrl = vehiclmageUrl.Split('~')[0];
                thumbImageUrl = vehiclmageUrl.Split('~')[1];
                vehicleIndex = vehiclmageUrl.Split('~')[2];

                //HtmlAnchor vehicleImageLink = ((HtmlAnchor)e.Item.FindControl("vehicleImageLink"));
                //vehicleImageLink.HRef = largeImageUrl;
                //vehicleImageLink.ID = vehicleIndex;
                HtmlAnchor vehicleImageLink = new HtmlAnchor();
                vehicleImageLink.HRef = largeImageUrl;
                //vehicleImageLink.ID = vehicleIndex;
                vehicleImageLink.Attributes.Add("id", vehicleIndex);
                vehicleImageLink.Attributes.Add("rel", "lightbox");


                //HtmlImage vehicleImage = ((HtmlImage)e.Item.FindControl("vehicleImage"));
                HtmlImage vehicleImage = new HtmlImage();
                vehicleImage.Src = thumbImageUrl;
                //vehicleImage.ID = vehicleIndex;
                vehicleImage.Attributes.Add("id", vehicleIndex);

                //vehicleImageLink.Controls.Add(vehicleImage);
                vehicleImageLink.Controls.Add(vehicleImage);
                e.Item.Controls.Add(vehicleImageLink);
            }
        }

    }
}